package com.handpay.nocardpay.baselibrary.bankmanager.view.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.account.model.bean.VerificationCodeBean;
import com.handpay.nocardpay.baselibrary.account.presenter.ModifyUserinfoPresenterImpl;
import com.handpay.nocardpay.baselibrary.account.presenter.VerfcodePresenterImpl;
import com.handpay.nocardpay.baselibrary.account.view.ISendVerfCodeView;
import com.handpay.nocardpay.baselibrary.account.view.ImodifyUserInfoView;
import com.handpay.nocardpay.baselibrary.bankmanager.presenter.BankInfoPresenterImpl;
import com.handpay.nocardpay.baselibrary.bankmanager.view.IModifyBankView;
import com.handpay.nocardpay.baselibrary.bankmanager.view.ISubBankView;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.main.mine.model.bean.MerchInfo;
import com.handpay.nocardpay.baselibrary.qualificationinfo.model.bean.BankList;
import com.handpay.nocardpay.baselibrary.qualificationinfo.model.bean.SubBankBean;
import com.handpay.nocardpay.baselibrary.qualificationinfo.widgets.HPSubBankEditView;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.widget.BankCardNoEditTextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by sxshi on 2017/8/15.
 */

public class ModifyBankFragment extends BaseFragment implements IModifyBankView, ISubBankView, ImodifyUserInfoView, ISendVerfCodeView {
    private static final int PAGESIZE = 30;
    private final int REQUT_SUB_CODE = 1000;

    private OptionsPickerView bankPickerView;
    private BankInfoPresenterImpl bankInfoPresenter;
    private MerchInfo merchInfo;

    private TextView bank_name, bank_handler, tv_phone;
    private TableRow tr_subbank;
    private TextView mGetVerfcode;
    private HPSubBankEditView sub_bank;
    private BankCardNoEditTextView bank_no;
    private EditText et_verfcode;
    private Button btn_submit;

    private List<String> bankNames;
    private List<BankList.ListBean> mMainBanks;
    private BankList.ListBean mSelectMainBank = new BankList.ListBean();

    //选择的支行信息
    private SubBankBean.ListBean subBank;


    private VerfcodePresenterImpl verfcodePresenter;
    private ModifyUserinfoPresenterImpl modifyUserinfoPresenter;
    private CountDownTimer mCountDownTimer;

    public static ModifyBankFragment newInstance(MerchInfo merchInfo) {
        Bundle args = new Bundle();
        args.putParcelable("merchInfo", merchInfo);
        ModifyBankFragment fragment = new ModifyBankFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_modify_bank;
    }

    @Override
    public String getFragmentTitle() {
        return getString(R.string.modify_bank);
    }

    @Override
    public void initView(View view) {
        merchInfo = getArguments().getParcelable("merchInfo");
        Toolbar mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        initToolbar(mToolbar, true, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWithPop(BankManagerFragment.newInstance(merchInfo));
            }
        });
        sub_bank = (HPSubBankEditView) view.findViewById(R.id.sub_bank);
        bank_no = (BankCardNoEditTextView) view.findViewById(R.id.bank_no);
        et_verfcode = (EditText) view.findViewById(R.id.et_verfcode);
        mGetVerfcode = (TextView) view.findViewById(R.id.btn_getcode);
        btn_submit = (Button) view.findViewById(R.id.btn_submit);

        bank_handler = (TextView) view.findViewById(R.id.bank_handler);
        tv_phone = (TextView) view.findViewById(R.id.tv_phone);
        bank_name = (TextView) view.findViewById(R.id.bank_name);
        tr_subbank = (TableRow) view.findViewById(R.id.tr_subbank);
        bankPickerView = new OptionsPickerView.Builder(_mActivity, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                sub_bank.setText("");
                bank_no.setText("");
                mSelectMainBank = mMainBanks.get(options1);
                String banName = mSelectMainBank.getBankName();
                if (!TextUtils.isEmpty(banName))
                    bank_name.setText(banName);
                if (!mSelectMainBank.getSubBankFlag().equals("1")) {
                    tr_subbank.setVisibility(View.GONE);
                } else {
                    tr_subbank.setVisibility(View.VISIBLE);
                }
            }
        }).setContentTextSize(21)
                .build();

    }

    @Override
    public void initListener() {
        bank_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bankPickerView.show();
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String etCode = et_verfcode.getText().toString();
                String cardNo = bank_no.getText().toString();
                cardNo = cardNo.replace(" ", "");
                if (null == mSelectMainBank) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.public_opening_bank_hint));
                    return;
                }
                if ("1".equals(mSelectMainBank.getSubBankFlag()) && null == subBank) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.public_opening_bank_hint));
                    return;
                }

                if (TextUtils.isEmpty(cardNo)) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.public_bank_Name_hint));
                    return;
                }

                if (TextUtils.isEmpty(etCode)) {
                    DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.verfcode));
                    return;
                }
                String bankCode = mSelectMainBank.getBankCode();
                queryBankInfo(etCode, cardNo, bankCode);
            }
        });
        sub_bank.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null == mSelectMainBank || "-1".equals(mSelectMainBank.getBankCode())) {
                    String title = _mActivity.getString(R.string.tip);
                    String message = _mActivity.getString(R.string.select_bank_tip);
                    DialogUtils.showAlertDialog(_mActivity, title, message, true);
                } else {
                    String keyword = s.toString();
                    querySubBankList(mSelectMainBank.getBankCode(), keyword);
                }
            }
        });
        sub_bank.setLisenter(new HPSubBankEditView.OnBankLisenter() {
            @Override
            public void onBankSelected(SubBankBean.ListBean listBean) {
                subBank = listBean;
                sub_bank.setText(subBank.getSubBankName());
            }
        });

        mGetVerfcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mGetVerfcode.setEnabled(false);
                mCountDownTimer.start();
                sendVerCode();
            }
        });
    }

    /**
     * 查询银行卡信息
     *
     * @param etCode
     * @param cardNo
     * @param bankCode
     */
    private void queryBankInfo(String etCode, String cardNo, String bankCode) {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(AccountUtils.getAccountPhone(_mActivity), 1, null));
        paramers.put(BaseProtocolKey.KEY_NAME, SecureManager.getInstance().des(merchInfo.getName(), 1, null));
        paramers.put(BaseProtocolKey.KEY_CARDNUM, SecureManager.getInstance().des(cardNo, 1, null));
        paramers.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        paramers.put(BaseProtocolKey.KEY_BANKCODE, bankCode);
        if (mSelectMainBank != null) {
            if ("1".equals(mSelectMainBank.getSubBankFlag()) && !TextUtils.isEmpty(subBank.getSubBankCode())) {
                paramers.put(BaseProtocolKey.KEY_SUBBANKCODE, subBank.getSubBankCode());
            }
        }
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.VERIFYCODE, etCode);
        paramers.put(BaseProtocolKey.ACTION, NoCardPayConstant.AUTHCODE_ACTION_MODIFYCARD);
        paramers.put(BaseProtocolKey.NEWBANKFLAG, "1");
        modifyUserinfoPresenter.modifyAccountBankInfo(paramers, true);
    }

    /**
     * 发送验证码
     */
    private void sendVerCode() {
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountPhone(_mActivity), 1, null));
        param.put(BaseProtocolKey.ACTION, NoCardPayConstant.AUTHCODE_ACTION_MODIFYCARD);
        param.put(BaseProtocolKey.PHONE, SecureManager.getInstance().des(AccountUtils.getAccountPhone(_mActivity), 1, null));
        if (NoCardPayConfig.isNoCardPay) {
            param.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        } else {
            param.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().FASTBILLCHANNEL);
        }
        verfcodePresenter.getVerificationCode(param, VerificationCodeBean.class, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        bankInfoPresenter = new BankInfoPresenterImpl(_mActivity);
        bankInfoPresenter.setModifyBankView(this);
        bankInfoPresenter.setiSubBankView(this);

        verfcodePresenter = new VerfcodePresenterImpl(_mActivity);
        verfcodePresenter.setSendVerfCodeView(this);

        modifyUserinfoPresenter = new ModifyUserinfoPresenterImpl(_mActivity);
        modifyUserinfoPresenter.setUserInfoView(this);

        bankNames = new ArrayList<>();
        mMainBanks = new ArrayList<>();
        mSelectMainBank = new BankList.ListBean();
        subBank = new SubBankBean.ListBean();

        if (savedInstanceState == null) {
            //初始化商户信息
            this.merchInfo = getArguments().getParcelable("merchInfo");
        } else {
            MerchInfo restoreMerchInfo = savedInstanceState.getParcelable("merchInfo");
            if (restoreMerchInfo != null) {
                this.merchInfo = restoreMerchInfo;
                HPLog.d(HPLog.SSX_TAG, "数据恢复:" + restoreMerchInfo.toString());
            }
        }

        String phoneNumber = AccountUtils.getAccountPhone(_mActivity);
        mSelectMainBank.setBankCode(merchInfo.getBankCode());
        mSelectMainBank.setBankName(merchInfo.getBankName());
        subBank.setSubBankCode(merchInfo.getSubBankCode());
        subBank.setSubBankName(merchInfo.getSubBranchName());
        if (!TextUtils.isEmpty(merchInfo.getSubBranchName()) && !TextUtils.isEmpty(merchInfo.getSubBankCode())) {
            mSelectMainBank.setSubBankFlag("1");
        }
        bank_name.setText(merchInfo.getBankName());
        bank_handler.setText(merchInfo.getName());
        tv_phone.setText(CommonUtils.formatPhoneNumber(phoneNumber));
        bank_no.setText(CommonUtils.formattingCard(merchInfo.getCardNum()));
        sub_bank.setText(merchInfo.getSubBranchName());

        mCountDownTimer = new CountDownTimer(NoCardPayConstant.MILLISINFUTURE, NoCardPayConstant.COUNTDOWNINTERVAL) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerfcode.setText((millisUntilFinished / 1000) + _mActivity.getString(R.string.letter_getVefCode));
            }

            @Override
            public void onFinish() {
                mGetVerfcode.setEnabled(true);
                mGetVerfcode.setText(_mActivity.getString(R.string.getvercode));
            }
        };
        if (TextUtils.isEmpty(merchInfo.getSubBankCode())) {
            tr_subbank.setVisibility(View.GONE);
        } else {
            tr_subbank.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 查询开户行列表
     */
    private void getBanList() {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        if (bankInfoPresenter != null) {
            bankInfoPresenter.queryBankList(paramers, BankList.class, true);
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        getBanList();
    }

    /**
     * 查询支行列表
     *
     * @param bankCode 银行编码
     * @param text     关键字
     */
    private void querySubBankList(String bankCode, String text) {
        HashMap<String, Object> paramers = new HashMap<String, Object>();
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put(BaseProtocolKey.BANKCODE, String.valueOf(bankCode));
        paramers.put(BaseProtocolKey.SEARCHTEXT, text);
        paramers.put(BaseProtocolKey.PAGESIZE, PAGESIZE);
        if (bankInfoPresenter != null) {
            bankInfoPresenter.querySubBankList(paramers, SubBankBean.class, false);
        }
    }

    @Override
    public void modifyUserInfoFinsh() {
        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.modifybank_success));
        pop();
    }

    @Override
    public void showSendVerfCodeSuccess() {
        DialogUtils.showToast(_mActivity, _mActivity.getString(R.string.send_verfcode_success));
    }

    @Override
    public void showBankList(BankList bankList) {
        mMainBanks = bankList.getList();
        for (BankList.ListBean listBean : bankList.getList()) {
            String bankName = listBean.getBankName();
            if (!bankNames.contains(bankName)) {
                bankNames.add(bankName);
            }
        }
        bankPickerView.setSelectOptions(getCurrentBankPosition(bankList.getList(), merchInfo.getBankCode()));
        bankPickerView.setPicker(bankNames);
    }

    @Override
    public void showSubBankList(SubBankBean subBankBean) {
        sub_bank.refreshBanks(subBankBean.getList());
    }

    /**
     * 获取当前用户开户行的位置
     *
     * @param beanList
     * @param bankCode
     * @return
     */
    public int getCurrentBankPosition(List<BankList.ListBean> beanList, String bankCode) {
        int result = -1;
        if (beanList.isEmpty() || TextUtils.isEmpty(bankCode)) {
            return -1;
        }
        for (int i = 0; i < beanList.size(); i++) {
            BankList.ListBean bean = beanList.get(i);
            if (bankCode.equals(bean.getBankCode())) {
                result = i;
                break;
            }
        }
        return result;
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == REQUT_SUB_CODE && resultCode == RESULT_OK) {
            HPLog.d(HPLog.SSX_TAG, data.size());
            if (data != null) {
                subBank = data.getParcelable("subBank");
                HPLog.d(HPLog.SSX_TAG, sub_bank.toString());
                sub_bank.setText(subBank.getSubBankName());
            }
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        startWithPop(BankManagerFragment.newInstance(merchInfo));
        return true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        HPLog.d(HPLog.SSX_TAG, "数据保存:" + merchInfo.toString());
        outState.putParcelable("merchInfo", merchInfo);
        super.onSaveInstanceState(outState);
    }
}
